package parse;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;


/**
 * @author 黄衡熙
 * @version 1.0
 */
public class DOMParse {
    public static void main(String[] args){
        try {
            //创建DOM工厂
            DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
            //通过工厂获取对应的解析器
            DocumentBuilder builder=factory.newDocumentBuilder();
            //解析文件,以上两部分都是固定的写法，接下来这一部只是参数是你指定的xml文件，其余都是固定模式
            Document document = builder.parse(DOMParse.class.getClassLoader().getResourceAsStream("student.xml"));
            //根据解析后的结果实现对应的功能
//            获取根标签
            Element root=document.getDocumentElement();
            System.out.println("标签名:"+root.getTagName());
//            获取标签中的属性
//            根据标签属性名获取属性值
            System.out.println("no属性值:"+root.getAttribute("no"));
            // 也可以获取指定标签中所有的属性
            NamedNodeMap attributes = root.getAttributes();
            System.out.println("节点数量:" + attributes.getLength());
            for (int i = 0; i < attributes.getLength(); i++) {
                System.out.println(attributes.item(i));
            }
//            获取指定元素的所有子节点
            NodeList childNodes=root.getChildNodes();
            System.out.println("节点数:"+childNodes.getLength());
            for(int i=0;i<childNodes.getLength();i++){
                Node node=childNodes.item(i);
                // 此时的5个子节点中存在文本节点与元素节
                if (node.getNodeType() == Node.ELEMENT_NODE) {
//                    System.out.println("这是元素节点");
                    Element student = (Element) node;
                    System.out.println("子标签名:" + student.getTagName());
                    NamedNodeMap attrs = student.getAttributes();
                    for (int j = 0; j < attrs.getLength(); j++) {
                        System.out.println(attrs.item(j));
                    }
                    NodeList sonList = student.getChildNodes();
                    System.out.println("student子节点数量:" + sonList.getLength());
                    for (int j = 0; j < sonList.getLength(); j++) {
                        Node sonNode = sonList.item(j);
                        if (sonNode.getNodeType() == Node.ELEMENT_NODE) {
                            System.out.println("姓名:" + sonNode.getTextContent());
                        }
                    }
                }
                if (node.getNodeType() == Node.TEXT_NODE) {
                    System.out.println("文本内容:" + node.getTextContent());
                }

            }
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
    }
}
